<?php
namespace app\admin\controller;
use think\Db;
use app\admin\model\SystemAdmin;
use service\CacheService;
use service\UtilService;
use think\Request;
use think\Response;
use think\facade\Session;
use think\facade\Url;
use think\captcha\Captcha;
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2020-05-22 16:38:22
 * @LastEditors: Sam
 * @LastEditTime: 2020-06-09 10:08:31
 */ 
class Login extends SystemBasic {
    /**
     * @name: 首页
     * @Author: Sam
     * @Date: 2020-05-22 16:39:48
     * @msg: 
     * @param {type} 
     * @return: 
     */
    public function index(){
        return $this->fetch();
    }

     /**
     * @name: 验证码
     * @Author: Sam
     * @Date: 2020-05-22 16:39:48
     * @msg: 
     * @param {type} 
     * @return: 
     */
    public function captcha(){
        ob_clean();
        $config =    [
            // 验证码字体大小
            'fontSize'    =>    30,    
            // 验证码位数
            'length'      =>    4,   
            // 关闭验证码杂点
            'useNoise'    =>    false, 
            'useCurve' => false,
            'reset' => true
        ];
        $captcha = new Captcha($config);
        return $captcha->entry("admin_login"); 
        exit();
    }
  /**
     * @name: 登录验证
     * @Author: Sam
     * @Date: 2020-05-22 16:39:48
     * @msg: 
     * @param {type} 
     * @return: 
     */
    public function verify(Request $request)
    {
        
        if(!$request->isPost()) return $this->failed('请登陆!');
        list($account,$pwd,$verify) = UtilService::postMore([
            'username','password','verify'
        ],$request,true);
        //检验验证码
     
        if(!captcha_check($verify,'admin_login')) return $this->failed('验证码错误，请重新输入');
        $error  = Session::get('login_error')?:['num'=>0,'time'=>time()];
        if($error['num'] >=5 && $error['time'] > strtotime('- 5 minutes'))
            return $this->failed('错误次数过多,请稍候再试!');
        //检验帐号密码
        $res = SystemAdmin::login($account,$pwd);
        if($res){
            Session::set('login_error',null);
            return $this->success('登录成功');
        }else{
            $error['num'] += 1;
            $error['time'] = time();
            Session::set('login_error',$error);
            return $this->failed(SystemAdmin::getErrorInfo('用户名错误，请重新输入'));
        }
    }
}

